package cn.edu.ldu.protocol;

import cn.edu.ldu.modules.controller.ChatMemberController;
import cn.edu.ldu.modules.entity.ChatMemberEntity;
import cn.edu.ldu.modules.entity.UserAccountEntity;
import cn.edu.ldu.util.Consts;
import cn.edu.ldu.views.modules.controller.UserController;
import com.alibaba.fastjson.JSON;
import cn.edu.ldu.modules.controller.ChatHistoryController;
import cn.edu.ldu.modules.entity.ChatHistoryEntity;
import cn.edu.ldu.util.Translate;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ChatInGroup {

    public ChatInGroup(Protocol pro) throws IOException {

        ChatHistoryEntity chatHistoryEntity = JSON.parseObject(pro.getData(), ChatHistoryEntity.class);
        List<ChatMemberEntity> chatMembers = null;
        try {
            chatMembers = ChatMemberController.getChatMember(chatHistoryEntity.getTalkerId(), pro.getToken());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(chatMembers == null)
            return;
        pro.setKey(Consts.P_CHAT_WITH_FRIEND);
        chatHistoryEntity.setSendTime(Calendar.getInstance().getTime());
        pro.setData(JSONObject.toJSONString(chatHistoryEntity));
        for(ChatMemberEntity cme : chatMembers){
            if(!cme.getUserId().equals(chatHistoryEntity.getSenderId())){
                if(!UserController.sendDataToUser(cme.getUserId(), pro)){
                    chatHistoryEntity.setStatus(0);  //用户不在线
                }else {  //用户在线
                    chatHistoryEntity.setStatus(1);
                }
            }
        }

        chatHistoryEntity.setSendTime(new Date());
        try {
            ChatHistoryController.addChatHistory(chatHistoryEntity, pro.getToken());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
